package com.iqiyi.pps.epg.web.webapp.listener;

import com.iqiyi.kiwi.utils.Configuration;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.ResourceUtils;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import java.io.File;

/**
 * Created with IntelliJ IDEA.
 * User: lishunlong
 * Date: 12-8-13
 * Time: 下午11:16
 * To change this template use File | Settings | File Templates.
 */
public class ConfigurationListener implements ServletContextListener {
    private final static String JAVA_VERSION = "java.version";
    private static final Logger logger = LoggerFactory.getLogger(ConfigurationListener.class);

    /**
     * Initialize the configurations.
     */
    public void contextInitialized(ServletContextEvent event) {
        logger.info("#####################################################");
        logger.info("#      project configuration initialization");
        String configFile = event.getServletContext().getInitParameter("configuration");
        try {
            File file = ResourceUtils.getFile(configFile);
            Configuration.getConfiguration().initConfig(file.getAbsolutePath());

            logger.info("#      Configuration File is " + file.getAbsolutePath());
            String version = System.getProperty(JAVA_VERSION);
            String version_ = Configuration.getString(JAVA_VERSION);
            if (version.equalsIgnoreCase(version_)) {
                logger.info("#      Configuration OK: Java Version is " + version);
            } else {
                logger.info("#      Configuration Failed ...");
            }

        } catch (Exception e) {
            logger.info("#      Configuration Failed ...");
            e.printStackTrace();
            System.exit(-1);
        }
        logger.info("#####################################################");
    }

    /**
     * Close the root web application context.
     */
    public void contextDestroyed(ServletContextEvent event) {
    }
}